
#include <stdio.h>
#include <string.h>
#include "engineSimRegisters.h"
typedef unsigned int Uns32;
typedef unsigned int Uns8;

#include "interrupt.h"
#include "spr_defs.h"

#define LOG(_FMT, ...)  printf( "APPLICATION: " _FMT,  ## __VA_ARGS__)
#define numberOfInterrupts 16

static inline void writeReg32(Uns32 address, Uns32 offset, Uns32 value)
{
    *(volatile Uns32*) (address + offset) = value;
}

static inline Uns32 readReg32(Uns32 address, Uns32 offset)
{
    return *(volatile Uns32*) (address + offset);
}

static inline Uns8 readReg8(Uns8 address, Uns8 offset)
{
    return *(volatile Uns8*) (address + offset);
}

static Uns32 swapByteOrder(Uns32 value) 
{
	return 	(value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 |
			(value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24;
}

volatile static Uns32 interruptCount = 0;
void interruptHandler(void)
{
	Uns32 value = swapByteOrder(readReg32(SENSOR_BASE, SENSOR_C0_DATA_ADDR)); // we have to convert from little to big endian
    LOG("Interrupt: Inject fuel immediately!\n");
	LOG("Value of sensor 1: 0x%x  %u\n", value, value);
	readReg32(INTERRUPT_BASE, INTERRUPT_C0_DATA_ADDR); // read register to force callback to unset interrupt
	interruptCount++;
}

int main(int argc, char **argv)
{
    //Attach the external interrupt handler for 'intr0'
    int_init();
    int_add(3, (void *)interruptHandler, NULL);
    int_enable(3);

    //Enable external interrupts
    Uns32 spr = MFSPR(17);
    spr |= 0x4;
    MTSPR(17, spr);
	
	while (interruptCount < numberOfInterrupts); // runs until max number of interrupts is reached
	
	return 1;
}


